package com.cyys.common.utils.file;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

public class FileUtil {
	/**
	 * 创建文件
	 * 
	 * @param basepath
	 *            根路径
	 * @param fileName
	 *            文件名
	 * @param fileContent
	 *             文件内容
	 * @return String
	 * @throws
	 * @2013-2-22 上午10:12:06
	 */
	public static boolean createFile(String basepath,
			String fileName, String fileContent) {
		Boolean bool = false;
		File dir = new File(basepath);
		if (!dir.exists()) {
			dir.mkdirs();
		}
		File file = new File(basepath + fileName);
		try {
			if(!file.exists())
				file.createNewFile();
			else{
				file.delete();
				file.createNewFile();
			}
		} catch (IOException e2) {
			e2.printStackTrace();
		}
		
		try {
			bool = writeFileContent(file, fileContent);
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		return bool;
	}
	
	/**
     * 向文件中写入内容
     * @param file 文件路径与名称
     * @param newstr  写入的内容
     * @return
     * @throws IOException
     */
    @SuppressWarnings("unused")
	public static boolean writeFileContent(File file,String newstr) throws IOException{
        Boolean bool = false;
        String filein = newstr+"\r\n";//新写入的行，换行
        String temp  = "";
        
        FileInputStream fis = null;
        InputStreamReader isr = null;
        BufferedReader br = null;
        FileOutputStream fos  = null;
        PrintWriter pw = null;
        try {
            //将文件读入输入流
            fis = new FileInputStream(file);
            isr = new InputStreamReader(fis);
            br = new BufferedReader(isr);
            StringBuffer buffer = new StringBuffer();
            
            //文件原有内容
            for(int i=0;(temp =br.readLine())!=null;i++){
                buffer.append(temp);
                // 行与行之间的分隔符 相当于“\n”
                buffer = buffer.append(System.getProperty("line.separator"));
            }
            buffer.append(filein);
            
            fos = new FileOutputStream(file);
            pw = new PrintWriter(fos);
            pw.write(buffer.toString().toCharArray());
            pw.flush();
            bool = true;
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            //不要忘记关闭
            if (pw != null) {
                pw.close();
            }
            if (fos != null) {
                fos.close();
            }
            if (br != null) {
                br.close();
            }
            if (isr != null) {
                isr.close();
            }
            if (fis != null) {
                fis.close();
            }
        }
        return bool;
    }
	
	
	/**
     * 删除文件
     * @param filePath 文件名称
     * @return
     */
    public static boolean delFile(String filePath){
        Boolean bool = false;
        File file  = new File(filePath);
        try {
            if(file.exists()){
                file.delete();
                bool = true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }
    
    
    /**
     * 获取缩略图名称
     * @param file
     * @param type 1：缩略图，2：中图
     * @return
     */
    public static String getThumbPath(String file,Integer type){
    	String filePath = file.substring(0,file.lastIndexOf("/") + 1);
    	String fileName = file.substring(file.lastIndexOf("/") + 1, file.length());
    	if(type == 1){
    		return filePath + "t_" + fileName;
    	}else if(type == 2){
    		return filePath + "m_" + fileName;
    	}else{
    		return filePath + "b_" + fileName;
    	}
    }
    
    public static void main(String[] args) {
		//FileUtil.createFile("D:/test/test/test/", "test.json", "123");
    	System.out.println(FileUtil.getThumbPath("e://test/test/rrr/test.jpg", 1));
	}

    /**
     * 将文件转成base64 字符串
     *
     * @param path 文件路径
     * @return *
     * @throws Exception
     */
    public static String encodeBase64File(String path) throws Exception {
        File file = new File(path);
        FileInputStream inputFile = new FileInputStream(file);
        byte[] buffer = new byte[(int) file.length()];
        inputFile.read(buffer);
        inputFile.close();
        return new BASE64Encoder().encode(buffer);
    }



    /**
     * 将base64字符解码保存文件
     *
     * @param base64Code
     * @param targetPath
     * @throws Exception
     */
    public static void decoderBase64File(String base64Code, String targetPath, String catalogue)
            throws Exception {
        File file = new File(catalogue);
        if(file.exists() == false){
            file.mkdirs();
        }
        byte[] buffer = new BASE64Decoder().decodeBuffer(base64Code);
        FileOutputStream out = new FileOutputStream(targetPath);
        out.write(buffer);
        out.close();
    }

}
